﻿/// <reference path="../GeneratedArtifacts/viewModel.js" />
/// <reference path="../Scripts/jquery.signalR-1.0.1.js" />

myapp.AddEditPlace.created = function (screen) {
    //set default values
    if (screen.useBingMap == null) {
        screen.useBingMap = true;
    }

    //events
    screen.Place.addChangeListener("Address", function (e) {
        if (screen.Place.Address != null && screen.Place.Address != "" && (screen.Place.Latitude == null || screen.Place.Longitude == null)) {
            if (screen.useBingMap) {
                $(bingMapDiv).lightswitchBingMapsControl("getPositionByAddress", screen.Place);
            }
            else {
                $(googleMapDiv).lightswitchGoogleMapsControl("getPositionByAddress", screen.Place);
            }
        }
    });

    //SignalR notifications
    $(function () {
        var hub = $.connection.placeHub;
        /*$.extend(placeHub, {
            changed: function (cid, message) {
                if (cid != $.connection.placeHub.id) {
                    screen.placeUpdates = message;
                }
            }
        });*/
        /*hub.client.broadcastMessage = function (message) {
            screen.placeUpdates = "server message " + message;
            setTimeout(function () {
                screen.placeUpdates = "";
            }, 5000);
        };
        hub.client.updatePlace = function (message) {
            screen.MessagesHistory = message;
            setTimeout(function () {
                screen.MessagesHistory = "";
            }, 5000);
        };
        // Add client-side hub methods that the server will call
        $.extend(hub.client, {
            connected: function (value) {
                screen.placeUpdates = value + " active connections to this place";
            },
            hubReset: function () {
                return null; //init();
            }
        });*/
        hub.client.addMessage = function (message) {
            screen.MessagesHistory = message;
        }
        // Start the connection
        $.connection.hub.start()
            //({ transport: 'longPolling' }, 
            .done(function () {
                //alert($.connection.hub.id);
                if (screen.Place.Id > 0) {
                    hub.server.join(screen.Place.Id);
                    //hub.client.connected(hub.server.getPlaceConectionsCount());
                }
            })
            .fail(function () {
                alert("Could not Connect! - ensure EnableCrossDomain = true");
            });
    });
};

myapp.AddEditPlace.Delete_execute = function (screen) {
    screen.Place.deleteEntity();
};

myapp.AddEditPlace.Place_Image_render = function (element, contentItem) {
    createImageUploader(element, contentItem, "max-width: 300px; max-height: 300px");
};

myapp.AddEditPlace.Details_postRender = function (element, contentItem) {
    contentItem.dataBind("screen.Place.Id", function (newValue) {
        contentItem.screen.details.displayName = "Place (" + (newValue == null ? "New" : newValue) + ")";
    });
    $.ajax({
        type: 'post',
        data: {},
        url: '../web/GetUserName.ashx',
        success: function success(result) {
            //screen.UserName = result; //cache user name for filtering
            if (contentItem.screen.Place.UserName != result) {
                /*var $saveBtn = $('div[title=Save]');
                if ($saveBtn) {
                    $saveBtn.hide();
                }*/
                $("msls-save-button").hide();
            }
        }
    });
};

myapp.AddEditPlace.DrivingMode_render = function (element, contentItem) {
    createBooleanSwitch(element, contentItem, 'Walking', 'Driving', '', '10em');
};

myapp.AddEditPlace.directionsItinerary_render = function (element, contentItem) {
    var directionsItineraryDiv = $('<div id="directionsItinerary"></div>').appendTo($(element));
};

var bingMapDiv;
myapp.AddEditPlace.bingMap_render = function (element, contentItem) {
    bingMapDiv = $('<div id="bmap_canvas" style="width: 100%; height: 100%" />').appendTo($(element));
    $(bingMapDiv).lightswitchBingMapsControl();
    $(bingMapDiv).lightswitchBingMapsControl("resetMap");
    setTimeout(function () {
        $(bingMapDiv).lightswitchBingMapsControl("getCurrentPosition", contentItem.screen.Place);
    }, 1000);
};

var googleMapDiv;
myapp.AddEditPlace.googleMap_render = function (element, contentItem) {
    googleMapDiv = $('<div id="gmap_canvas" style="width: 100%; height: 100%" />').appendTo($(element)); //class="gmap3" 
    $(googleMapDiv).lightswitchGoogleMapsControl();
    setTimeout(function () {
        $(googleMapDiv).lightswitchGoogleMapsControl("getCurrentPosition", contentItem.screen.Place);
    }, 0);
};

myapp.AddEditPlace.useBingMap_render = function (element, contentItem) {
    createMapSwitch(element, contentItem, 'Bing', 'Google', '10em');
};

myapp.AddEditPlace.beforeApplyChanges = function (screen) {
    /*$.ajax({
        type: 'post',
        data: {},
        url: '../web/GetUserName.ashx',
        success: function success(result) {
            if (screen.Place.UserName != null && screen.Place.UserName != result) {
                screen.validationResults = [new msls.ValidationResult(screen.Place.details.properties.UserName, "The user can't modify place created by other user")];
                return;
            }
        }
    });*/
    
    var place = screen.Place, contentItem1 = screen.findContentItem("Latitude"), contentItem2 = screen.findContentItem("Longitude");
    if ((place.details.entityState === msls.EntityState.added || place.details.entityState === msls.EntityState.modified) && contentItem1.validationResults.length === 0 && place.Latitude == null) {
        contentItem1.validationResults = [new msls.ValidationResult(place.details.properties.Latitude, "Cannot be blank")];
    }

    if ((place.details.entityState === msls.EntityState.added || place.details.entityState === msls.EntityState.modified) && contentItem2.validationResults.length === 0 && place.Longitude == null) {
        contentItem2.validationResults = [new msls.ValidationResult(place.details.properties.Longitude, "Cannot be blank")];
    }
};

myapp.AddEditPlace.DrawMapRoute_execute = function (screen) {
    if (navigator && navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(geo_success);
    } else {
        alert("Error. No Gps signal");
        function geo_success(position) {
            var fromPlace = { Address: "Current Position", Latitude: position.coords.latitude, Longitude: position.coords.longitude };
            if (screen.useBingMap) {
                $(bingMapDiv).lightswitchBingMapsControl("getCurrentPosition", fromPlace);
            }
            else {
                $(googleMapDiv).lightswitchGoogleMapsControl("getCurrentPosition", fromPlace);
            }

            var toPlace = screen.Place;

            if (screen.useBingMap) {
                $(bingMapDiv).lightswitchBingMapsControl("createMovementRoute", fromPlace, toPlace, screen.DrivingMode, screen.TrafficMode);
            }
            else {
                $(googleMapDiv).lightswitchGoogleMapsControl("createMovementRoute", fromPlace, toPlace, screen.DrivingMode, screen.TrafficMode);
            }
        };
    }
};

myapp.AddEditPlace.TrafficMode_render = function (element, contentItem) {
    createBooleanSwitch(element, contentItem, 'Show', 'Hide', '', '10em');
};


myapp.AddEditPlace.MapHelp_render = function (element, contentItem) {
    $('<a class="ui-icon-alt" href="#popupInfo" data-role="button" data-iconpos="notext" data-icon="info" data-inline="true" data-transition="pop" data-rel="popup" data-theme="e">Learn more</a><div class="ui-content" id="popupInfo" style="max-width: 350px;" data-role="popup" data-theme="e">  <p>OIf Lat/Long are blank, marker on the map reflects <strong>current position</strong> based on your browser/device geolocation. When you change marker position it will try to resolve address, latitude and longitude.</p></div>').appendTo($(element));
};

var flickrImagesDiv;
myapp.AddEditPlace.FlickrImages_render = function (element, contentItem) {
    flickrImagesDiv = $('<div id="FlickrImagesDiv"></div>').appendTo($(element));
    $(flickrImagesDiv).lightswitchFlickrControl();
    $(flickrImagesDiv).lightswitchFlickrControl("searchPhotos", contentItem.screen.Place);
};

myapp.AddEditPlace.DeepLink_postRender = function (element, contentItem) {
    // The hash is present on non-home screens.  Since we're
    // doing this on the home screen we could skip this part
    // but here it is for completeness.
    var hashPos = window.location.href.indexOf("#");
    if (hashPos >= 0)
        var baseUrl = window.location.href.substr(0, hashPos);
    else
        var baseUrl = window.location.href;
    var fullUrl = baseUrl + "?entity=MMC_Content/Places(" +
                  contentItem.screen.Place.Id + ")";
    contentItem.screen.PlaceUrl = fullUrl;
};